package org.abettor.pushbox.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Random;

import org.abettor.android.ads.YoumiManager;
import org.abettor.pushbox.config.Config;
import org.abettor.pushbox.db.PushBoxDbHelper;
import org.abettor.pushbox.db.PushBoxMapBeanManage;
import org.abettor.pushbox.map.AsyncGenerateMapThumbImage;
import org.abettor.pushbox.map.Boxmap;
import org.abettor.pushbox.map.BoxmapUtil;
import org.abettor.pushbox.map.AsyncGenerateMapThumbImage.ImageCallback;
import org.abettor.pushbox.model.PushBoxMapBean;
import org.abettor.pushbox.upload.UploadMap;
import org.abettor.pushbox.upload.UploadMap.UpdateUploadMap;
import org.abettor.pushbox.util.FileUtil;
import org.abettor.pushbox.R;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.SpannedString;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 自制地图的列表
 * 
 * @author jzh
 */
public class SelfmakeMapActivity extends ListActivity {
	private final float WIDTH = 70, HEIGHT = 70;
	private final int SHOW_AD = 13579;
	private static final int DELETED_ID = Menu.FIRST;
	private static final int VIEWRESULT_ID = Menu.FIRST + 1;
	private static final int UPLOAD_ID = Menu.FIRST + 2;
	private static final int RESTART_ID = Menu.FIRST + 3;
	private static final int RE_EDITMAP_ID = Menu.FIRST + 5;
	private static final int ADD_MAP_ID = Menu.FIRST + 6;
	private SQLiteDatabase base;
	private PushBoxDbHelper dbHelper;
	private PushBoxMapBeanManage manage = null;
	private UploadMap uploadMapBean = null;
	private Cursor cursor;// 查询数据库的游标
	private YoumiManager youmi = new YoumiManager(this);
	private Handler mHandler = new Handler();
	private Handler youmiHandle = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == SHOW_AD) {
				// 按照一定的概率显示广告
				Random rand = new Random(System.currentTimeMillis());
				int val = rand.nextInt(99);
				if (val < 20) {
					youmi.showYoumi(YoumiManager.Position.top, Color.WHITE,
							Color.BLACK, 0xAA);
				}
			}

			super.handleMessage(msg);
		}
	};
	private Thread youmiDelayThread = new Thread() {
		@Override
		public void run() {
			try {
				Thread.sleep(200);
				Message msg = new Message();
				msg.what = SHOW_AD;
				youmiHandle.sendMessage(msg);
			} catch (InterruptedException e) {
				Log.d(this.getClass().getName(), "", e);
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.selfmake_map_activity);
		dbHelper = new PushBoxDbHelper(this);
		base = dbHelper.getWritableDatabase();// 获得数据库的链接
		this.registerForContextMenu(this.getListView());
		uploadMapBean = new UploadMap(this);
		manage = new PushBoxMapBeanManage(this);// 设置管理
		youmiDelayThread.start();
	}
	@Override
	protected void onResume(){
		super.onResume();
		cursor = this.getCursor();
		MapListAdapter adapter = new MapListAdapter(this, cursor);
		this.setListAdapter(adapter);
		startManagingCursor(cursor);
	}
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Intent in = new Intent();
		TextView tv = (TextView) v.findViewWithTag("isDraft");
		if (tv.getText() == null || tv.getText().toString().equals("")) {// 非草稿
																			// 判断是否已经完成
			TextView resolved = (TextView) v.findViewWithTag("isSoveld");
			CharSequence seq = resolved.getText();
			SpannedString builder = (SpannedString) seq;
			Integer[] it = builder.getSpans(0, builder.length(), Integer.class);
			if (it[0] == 0) {// 未解决
				in.setClass(this, SelfPushBoxActivity.class);
			} else {// 已解决
				in.setClass(this, SelfShowResultActivity.class);
			}
		} else {// 草稿
			in.setClass(this, MakeMapActivity.class);
		}
		Bundle extras = new Bundle();
		extras.putInt("_id", (int) id);
		in.putExtras(extras);
		startActivity(in);
	}

	/**
	 * 创建系统菜单
	 */
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
		menu.setHeaderTitle(this.getString(R.string.mod_private_map));
		menu.add(0, DELETED_ID, 0, R.string.del_map);
		Cursor cursor = (Cursor) getListAdapter().getItem(info.position);
		if (cursor == null) {
			return;
		}
		int index = cursor.getColumnIndex(PushBoxDbHelper.PUSH_BOX_ISDRAFT);
		String isDraft = cursor.getString(index);
		if (!"1".equals(isDraft)) {// 判断是否为草稿
			index = cursor.getColumnIndex(PushBoxDbHelper.PUSH_BOX_SOLVED);
			String isSovled = cursor.getString(index);
			if ("1".equals(isSovled)) {// 已经解决完了
				// menu.add(0, VIEWRESULT_ID, 1, R.string.show_result);
				// menu.add(0, RESTART_ID, 3, R.string.restart_game);
			}
			// 判断该地图是否已经上传过
			index = cursor.getColumnIndex(PushBoxDbHelper.PUSH_BOX_HASUPLOADED);
			String isUploaded = cursor.getString(index);
			if (!"1".equals(isUploaded)) {
				menu.add(0, UPLOAD_ID, 2, R.string.upload_result);
			}
		} else {
			menu.add(0, RE_EDITMAP_ID, 1, R.string.re_edit_map);
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem aItem) {
		switch (aItem.getItemId()) {
		case DELETED_ID:// 删除地图
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) aItem
					.getMenuInfo();
			deleteDraft((int) info.id);
			break;
		case VIEWRESULT_ID:// 查询地图的结果
		case UPLOAD_ID:// 上传地图
			info = (AdapterView.AdapterContextMenuInfo) aItem.getMenuInfo();
			uploadMap((int) info.id);
			break;
		case RESTART_ID:// 重新开始地图
		case RE_EDITMAP_ID:// 重新编辑地图
		}
		return false;
	}

	// 上传地图的操作
	private void uploadMap(final int id) {
		String filename = manage.getFileName(id);
		// 读取图片的操作
		try {
			byte[] data = FileUtil.readFileByPath(Config.getSelfBasePath()
					+ File.separator + filename + ".map");
			UpdateUploadMap in = new UpdateUploadMap() {
				@Override
				public void update(int ids) {
					manage.updateUploadStateSuccess(id, ids);
					// 更新地图的状态
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							MapListAdapter adapter = (MapListAdapter) SelfmakeMapActivity.this
									.getListAdapter();
							cursor.close();
							cursor = getCursor();
							adapter.changeCursor(cursor);
							adapter.notifyDataSetChanged();
						}
					});
				}
			};
			uploadMapBean.uploadMap(data, in);
		} catch (IOException e) {
		}
	}

	// 删除地图的操作
	private void deleteDraft(final int id) {
		if (id == -1) {
			return;
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		AlertDialog alert = builder.create();
		alert.setTitle(R.string.del_map);
		alert.setMessage(this.getText(R.string.del_map_confirm));
		alert.setButton(DialogInterface.BUTTON_POSITIVE,
				this.getText(android.R.string.ok),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						String filename = manage.getFileName(id);
						manage.delPushBoxMapBean(id);
						deleteTheFile(filename);
						Toast.makeText(SelfmakeMapActivity.this,
								R.string.del_map_success, Toast.LENGTH_SHORT)
								.show();
						MapListAdapter adapter = (MapListAdapter) SelfmakeMapActivity.this
								.getListAdapter();
						cursor.close();
						cursor = getCursor();
						adapter.changeCursor(cursor);
						adapter.notifyDataSetChanged();
					}
				});
		alert.setButton(DialogInterface.BUTTON_NEGATIVE,
				this.getText(android.R.string.cancel),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
		alert.show();
	}

	// 删除文件的操作
	private void deleteTheFile(String filename) {
		try {
			File file = new File(Config.getSelfBasePath() + File.separator
					+ filename + ".map");
			if (file.exists()) {
				file.delete();
			}
			file = new File(Config.getSelfBasePath() + File.separator
					+ filename + ".thumb");
			if (file.exists()) {
				file.delete();
			}
			file = new File(Config.getSelfBasePath() + File.separator
					+ filename + ".draft");
			if (file.exists()) {
				file.delete();
			}
			file = new File(Config.getSelfBasePath() + File.separator
					+ filename + ".step");
			if (file.exists()) {
				file.delete();
			}
		} catch (Exception e) {
		}
	}

	// 生成列表的adapter
	private class MapListAdapter extends CursorAdapter {
		public MapListAdapter(Context context, Cursor c) {
			super(context, c);
		}

		@Override
		public void bindView(View view, Context context, Cursor corsor) {
			ViewGroup theparent = (ViewGroup) view;
			setView(theparent, cursor);
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			LayoutInflater inflater = SelfmakeMapActivity.this
					.getLayoutInflater();
			ViewGroup theparent = (ViewGroup) inflater.inflate(
					R.layout.selfmake_map_list_item, parent, false);
			return theparent;
		}

		private void setView(ViewGroup group, Cursor cursor) {
			TextView isUpload = (TextView) group.findViewWithTag("isUpload");
			isUpload.setVisibility(View.GONE);
			isUpload.setText("");
			TextView isSovled = (TextView) group.findViewWithTag("isSoveld");
			isSovled.setText("");
			isSovled.setVisibility(View.GONE);
			TextView createTime = (TextView) group
					.findViewWithTag("createTime");
			createTime.setText("");
			TextView isDraft = (TextView) group.findViewWithTag("isDraft");
			isDraft.setText("");
			isDraft.setVisibility(View.GONE);
			// 设置地图状态
			int index = cursor
					.getColumnIndex(PushBoxDbHelper.PUSH_BOX_CREATE_TIME);
			String createTimeStr = cursor.getString(index);
			createTime.setText(SelfmakeMapActivity.this
					.getText(R.string.map_create_time) + ":\n" + createTimeStr);
			// 获得是否为草稿
			index = cursor.getColumnIndex(PushBoxDbHelper.PUSH_BOX_ISDRAFT);
			int idraft = cursor.getInt(index);
			if (idraft == 1) {// 草稿
				SpannableStringBuilder builder = new SpannableStringBuilder();
				builder.append(SelfmakeMapActivity.this
						.getText(R.string.map_isdraft));
				builder.setSpan(idraft, 0, builder.length(),
						Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				isDraft.setText(builder);
				isDraft.setVisibility(View.VISIBLE);
			} else {// 非草稿,判断是否已解决
				index = cursor.getColumnIndex(PushBoxDbHelper.PUSH_BOX_SOLVED);
				int solved = cursor.getInt(index);
				SpannableStringBuilder builder = new SpannableStringBuilder();
				String tmp = null;
				if (solved == 0) {// 未解决
					tmp = SelfmakeMapActivity.this.getText(
							R.string.map_not_resolved).toString();
				} else {// 已解决
					tmp = SelfmakeMapActivity.this.getText(
							R.string.map_resolved).toString();
					int i = cursor
							.getColumnIndex(PushBoxDbHelper.PUSH_BOX_RESOLVE_TIME);
					String reSolvedTimeStr = cursor.getString(i);
					tmp = tmp.toString() + "(" + reSolvedTimeStr + ")";
				}
				builder.append(tmp);
				builder.setSpan(solved, 0, tmp.length(),
						Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				isSovled.setText(builder);
				isSovled.setVisibility(View.VISIBLE);
				// 判断是否上传过
				SpannableStringBuilder upBuilder = new SpannableStringBuilder();
				index = cursor
						.getColumnIndex(PushBoxDbHelper.PUSH_BOX_HASUPLOADED);
				int uploaded = cursor.getInt(index);
				String upStr = null;
				if (uploaded == 0) {// 未上传
					upStr = SelfmakeMapActivity.this.getText(
							R.string.map_not_uploaded).toString();
				} else {// 已上传
					upStr = SelfmakeMapActivity.this.getText(
							R.string.map_uploaded).toString();
					int i = cursor
							.getColumnIndex(PushBoxDbHelper.PUSH_BOX_UPLOADED_TIME);
					String uploadedTimeStr = cursor.getString(i);
					upStr = upStr + "(" + uploadedTimeStr + ")";
				}
				upBuilder.append(upStr);
				upBuilder.setSpan(uploaded, 0, upStr.length(),
						Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				isUpload.setText(upBuilder);
				isUpload.setVisibility(View.VISIBLE);
			}
			// 获得文件的名字
			index = cursor.getColumnIndex(PushBoxDbHelper.PUSH_BOX_NAME);
			String fileName = cursor.getString(index);
			ImageView thumbImage = (ImageView) group
					.findViewWithTag("thumbImage");
			// 回掉显示图片的操作
			setImageView(thumbImage, fileName, idraft);
		}
	}

	private Bitmap readBitmap(File file) {
		FileInputStream is;
		try {
			is = new FileInputStream(file);
			Bitmap bitmap = BitmapFactory.decodeStream(is);
			is.close();
			return bitmap;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	private void setImageView(final ImageView thumbImage,
			final String fileName, final int isDrafed) {
		// 先判断文件是否存在，存在的话同步操作，否则异步操作
		String filepath = null;
		if (isDrafed != 1) {
			filepath = Config.getSelfBasePath() + File.separator + fileName
					+ ".thumb";
		} else {
			filepath = Config.getSelfBasePath() + File.separator + fileName
					+ ".draft";
		}
		File file = new File(filepath);
		Bitmap bmp = null;
		if (file.exists()) {// 读取存在的文件
			bmp = readBitmap(file);
			if (bmp != null) {
				thumbImage.setImageBitmap(bmp);
				return;
			}
		}
		// 文件不存在，只好异步操作了
		ImageCallback callback = new ImageCallback() {
			@Override
			public void processImage(Bitmap bit) {
				thumbImage.setImageBitmap(bit);
			}
		};
		AsyncGenerateMapThumbImage as = new AsyncGenerateMapThumbImage(WIDTH,
				HEIGHT, callback, this) {
			@Override
			public String getMapFilePath() {
				return Config.getSelfBasePath() + File.separator + fileName
						+ ".map";
			}

			@Override
			public String getThumbNailPath() {
				if (isDrafed != 1) {
					return Config.getSelfBasePath() + File.separator + fileName
							+ ".thumb";
				} else {
					return Config.getSelfBasePath() + File.separator + fileName
							+ ".draft";
				}
			}

			@Override
			protected Bitmap generateImage() {
				if (isDrafed == 1) {// 草稿
					byte[] buf = null;
					try {
						buf = readFile();
					} catch (IOException e) {
					}
					if (buf == null)
						return null;
					Boxmap map = BoxmapUtil.paraArrayToMap(buf);// 生成地图
					String filepath = getThumbNailPath();
					Bitmap bmp = null;
					mapThumbnailDraw.setMap(map);
					bmp = mapThumbnailDraw.drawDraftImage();
					// 在本地存一份
					generateThumbnail(bmp, filepath);
					return bmp;
				} else {// 非草稿
					return super.generateImage();
				}
			}
		};
		as.start();
	}

	private Cursor getCursor() {
		Cursor c = base.query(PushBoxDbHelper.PUSH_BOX_TABLE_NAME,
				new String[] { PushBoxDbHelper.PUSH_BOX_ID,
						PushBoxDbHelper.PUSH_BOX_SOLVED,
						PushBoxDbHelper.PUSH_BOX_ISDRAFT,
						PushBoxDbHelper.PUSH_BOX_MAP_FILENAME,
						PushBoxDbHelper.PUSH_BOX_RESOLVE_TIME,
						PushBoxDbHelper.PUSH_BOX_CREATE_TIME,
						PushBoxDbHelper.PUSH_BOX_NAME,
						PushBoxDbHelper.PUSH_BOX_HASUPLOADED,
						PushBoxDbHelper.PUSH_BOX_UPLOADED_TIME },
				PushBoxDbHelper.PUSH_BOX_TYPE + "="
						+ PushBoxMapBean.SELFMAKE_TYPE, null, null, null,
				PushBoxDbHelper.PUSH_BOX_CREATE_TIME + " desc");
		return c;
	}

	/**
	 * 创建系统菜单
	 */
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(0, ADD_MAP_ID, 0, R.string.add_map).setIcon(
				android.R.drawable.ic_menu_add);
		return result;
	}

	/**
	 * 系统菜单执行的操作
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case ADD_MAP_ID:
			Intent addIntent = new Intent();
			addIntent.setClass(this, MakeMapActivity.class);
			startActivity(addIntent);
			break;
		}
		return super.onOptionsItemSelected(item);
	}
}
